package com.innext.dsx.ui.my.fragment;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innext.dsx.R;
import com.innext.dsx.app.App;
import com.innext.dsx.base.BaseFragment;
import com.innext.dsx.config.Constant;
import com.innext.dsx.dialog.ActionSheetDialog;
import com.innext.dsx.dialog.AlertFragmentDialog;
import com.innext.dsx.events.FragmentRefreshEvent;
import com.innext.dsx.events.UIBaseEvent;
import com.innext.dsx.ui.authentication.activity.PerfectInformationActivity;
import com.innext.dsx.ui.main.MainActivity;
import com.innext.dsx.ui.main.WebViewActivity;
import com.innext.dsx.ui.my.activity.MoreActivity;
import com.innext.dsx.ui.my.activity.TransactionRecordActivity;
import com.innext.dsx.ui.my.bean.MoreContentBean;
import com.innext.dsx.ui.my.contract.MyContract;
import com.innext.dsx.ui.my.presenter.MyPresenter;
import com.innext.dsx.util.SpUtil;
import com.innext.dsx.util.StringUtil;
import com.innext.dsx.util.ToastUtil;
import com.innext.dsx.util.Tool;
import com.innext.dsx.widget.loading.LoadingLayout;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import cn.udesk.UdeskConst;
import cn.udesk.UdeskSDKManager;


/**
 * 作者：黑哥 on 2016/9/20 13:26
 * <p>
 * 更多页面
 */
public class MoreFragment extends BaseFragment<MyPresenter> implements View.OnClickListener, MyContract.View
,SwipeRefreshLayout.OnRefreshListener{
    public static MoreFragment fragment;
    @BindView(R.id.loading_layout)
    LoadingLayout mLoadingLayout;
    @BindView(R.id.iv_query)
    ImageView ivQuery;
    @BindView(R.id.tc_progress)
    TextView mTcProgress;
    @BindView(R.id.tv_remaining_borrow)
    TextView mTvRemainingBorrow;
    @BindView(R.id.tv_my_bank)
    TextView mTvMyBank;
    @BindView(R.id.tv_invit_code)
    TextView mTvInvitCode;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;
//    @BindView(R.id.tv_qq_group)
//    TextView mTvQqGroup;
    private MainActivity mActivity;
    private MoreContentBean mMoreContentBean;
    //客服电话
    private String serverPhone;


    public static MoreFragment getInstance() {
        if (fragment == null)
            fragment = new MoreFragment();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_more_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mActivity = (MainActivity) getActivity();
        EventBus.getDefault().register(this);
        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext,R.color.theme_color));
        mRefresh.setOnRefreshListener(this);
        if (App.getConfig().getLoginStatus()) {
            mPresenter.getInfo();
        }
        //设置
        mTitle.setTitle(false, StringUtil.changeMobile(SpUtil.getString(Constant.CACHE_TAG_USERNAME)));
        mTitle.setRightTitle(R.mipmap.setting, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mContext,"my_setting");
//                if (mMoreContentBean==null){
//                    mPresenter.getInfo();
//                }else{
                    Intent intent = new Intent(mActivity, MoreActivity.class);
                    intent.putExtra("bean", mMoreContentBean);
                    startActivity(intent);
//                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FragmentRefreshEvent event) {
        if (UIBaseEvent.EVENT_BANK_CARD_SUCCESS==event.getType()||//银行卡绑定或修改成功
            UIBaseEvent.EVENT_LOGIN==event.getType() || //登录成功
            UIBaseEvent.EVENT_REPAY_SUCCESS==event.getType()||  //还款成功
            UIBaseEvent.EVENT_REALNAME_AUTHENTICATION_SUCCESS==event.getType()||    //实名认证成功
            UIBaseEvent.EVENT_LOAN_SUCCESS==event.getType()||   //借款申请成功
            UIBaseEvent.EVENT_LOAN_FAILED ==event.getType()){   //借款申请失败
            if (UIBaseEvent.EVENT_LOGIN==event.getType()){
                mTitle.setTitle(false, StringUtil.changeMobile(SpUtil.getString(Constant.CACHE_TAG_USERNAME)));
            }
            if (App.getConfig().getLoginStatus()) {
                mPresenter.getInfo();
            }
        }
    }

    /**
     * 设置数据
     */
    private void setData(MoreContentBean mMoreContentBean) {
        // 0 不显示 1显示
//        if(mMoreContentBean.getCredit_info()!=null){
//            if(Constant.RISK_STATUS.equals(mMoreContentBean.getCredit_info().getRisk_status())){ivQuery.setVisibility(View.VISIBLE);}
//            else ivQuery.setVisibility(View.GONE);
//        }
        if (mMoreContentBean.getCard_info() != null) {
            if (!StringUtil.isBlank(mMoreContentBean.getCard_info().getBank_name()) && !StringUtil.isBlank(mMoreContentBean.getCard_info().getCard_no_end())) {
                mTvMyBank.setText(mMoreContentBean.getCard_info().getBank_name() + "(" + mMoreContentBean.getCard_info().getCard_no_end() + ")");
            } else {
                mTvMyBank.setText("");
            }
        }
        mTvInvitCode.setText(mMoreContentBean.getInvite_code());
        setCreditLimitAnimation(mTcProgress, Integer.valueOf(mMoreContentBean.getCredit_info().getCard_amount()) / 100);
        mTvRemainingBorrow.setText("剩余可借：" + Integer.valueOf(mMoreContentBean.getCredit_info().getCard_unused_amount()) / 100 + "元");
        serverPhone = mMoreContentBean.getService().getService_phone();
//        if (null!=mMoreContentBean.getService()){
//            mTvQqGroup.setText(mMoreContentBean.getService().getQq_group());
//        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showToast("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.showToast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的"); //统计页面，"MainScreen"为页面名称，可自定义
        MobclickAgent.onEvent(mContext, "my");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        fragment = null;
    }

    private void setCreditLimitAnimation(final TextView view, final int maxMoney) {
        ValueAnimator animator = ValueAnimator.ofInt(0, maxMoney)
                .setDuration(1000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.start();
    }

    @OnClick({R.id.layout_perfect, R.id.layout_lend_record, R.id.layout_bank,
            R.id.layout_invitation_code, R.id.layout_invitation, R.id.layout_message,
            R.id.layout_help, R.id.layout_qq,R.id.iv_query})
    public void onClick(View view) {
        /**
         * 防止多次点击进入重复界面
         * 针对于startActivity启动
         * */
        if (Tool.isFastDoubleClick())
            return;

        switch (view.getId()) {
            case R.id.layout_perfect://完善资料
                MobclickAgent.onEvent(mContext,"perfect_information");
                startActivity(PerfectInformationActivity.class);
                break;
            case R.id.layout_lend_record://借款记录
                MobclickAgent.onEvent(mContext,"lend_record");
                startActivity(TransactionRecordActivity.class);
                break;
            case R.id.layout_bank://收款银行卡
                MobclickAgent.onEvent(mContext,"proceeds_bank");
                if (mMoreContentBean != null) {
                    try {
                        if (mMoreContentBean.getVerify_info().getReal_verify_status().equals("1")) {
                            //if (mMoreContentBean.getVerify_info().getReal_bind_bank_card_status().equals("1")) {
                                Intent intent = new Intent(mActivity, WebViewActivity.class);
                                intent.putExtra("url", mMoreContentBean.getCard_url());
                                startActivity(intent);
                            /*} else {
                                startActivity(AddBankCardActivity.class);
                            }*/
                        } else {
                            new AlertFragmentDialog.Builder(mActivity)
                                    .setContent("亲,请先填写个人信息哦~")
                                    .setRightBtnText("确定")
                                    .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                        @Override
                                        public void dialogRightBtnClick() {
                                            startActivity(PerfectInformationActivity.class);
                                        }
                                    }).setCancel(true).build();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mPresenter.getInfo();
                }
                break;
            case R.id.layout_invitation_code://我的邀请码
                Bundle invitation = new Bundle();
                invitation.putString("url", App.getConfig().INVITATION_CODE);
                startActivity(WebViewActivity.class, invitation);
                break;
            case R.id.layout_invitation://推荐给好友
                MobclickAgent.onEvent(mContext,"invitation");
                if (mMoreContentBean != null) {
                    new ShareAction(mActivity).setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                            .withTitle(mMoreContentBean.getShare_title())
                            .withText(mMoreContentBean.getShare_body())
                            .withTargetUrl(mMoreContentBean.getShare_url())
                            .withMedia(new UMImage(mActivity, mMoreContentBean.getShare_logo()))
                            .setCallback(umShareListener).open();
                }
                break;
            case R.id.layout_message://消息中心
                MobclickAgent.onEvent(mContext,"message");
                Bundle message = new Bundle();
                message.putString("url", App.getConfig().ACTIVITY_CENTER);
                startActivity(WebViewActivity.class, message);
                break;
            case R.id.layout_help://帮助中心
                MobclickAgent.onEvent(mContext,"my_help");
                Bundle help = new Bundle();
                help.putString("url", App.getConfig().HELP);
                startActivity(WebViewActivity.class, help);
                break;
            case R.id.iv_query://顶部问号
                MobclickAgent.onEvent(mContext,"my_query");
                new AlertFragmentDialog.Builder(mActivity)
                        .setContent("额度不够？赶紧提额吧！")
                        .setRightBtnText("去提额")
                        .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                intent.putExtra("improveUrl", Constant.LIMIT_URL);
                                startActivity(intent);
                            }
                        })
                        .setCancel(true).build();
                break;
            case R.id.layout_qq://联系客服
//                MobclickAgent.onEvent(mContext,"customer_service");
//                Information info = new Information();
//                info.setAppkey(Constant.SOBOT_KEY);
//                info.setUseVoice(true);//是否使用语言
//                info.setPhone(SpUtil.getString(Constant.CACHE_TAG_USERNAME));//传入用户名手机号
//                info.setRealname(SpUtil.getString(Constant.CACHE_TAG_REAL_NAME));//用户名
//                //开启 离线消息
//                SobotApi.initSobotChannel(mContext);
//                //设置隐藏几分钟之前的历史消息
//                //time-查询时间(例:100-表示从现在起前100分钟的会话)  默认为0  表示不隐藏历史记录
//                //设置当用户返回时推送评价 用户信息
//                SobotApi.startSobotChat(mActivity, info);
                /*if(mMoreContentBean!=null&&mMoreContentBean.getService()!=null){
                    String qqUrl=mMoreContentBean.getService().getQq_group().trim();
                    if(!Tool.isBlank(qqUrl)) {
//                        String qq_url = "mqqwpa://im/chat?chat_type=crm&uin=" + qqUrl + "&version=1&src_type=web&web_src=file:://";
                        String qq_url = "mqqwpa://im/chat?chat_type=wpa&uin="+qqUrl;
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qq_url)));
//                            QQAuth mqqAuth = QQAuth.createInstance("1106060383", mContext); // 10000000为你申请的APP_ID,mContext是上下文
//                            WPA mWPA = new WPA(getActivity(), mqqAuth.getQQToken());
//                            String ESQ = qqUrl;  //512821255为客服QQ号
//                            int ret = mWPA.startWPAConversation(getActivity(), ESQ,"米乐贷"); //客服QQ
//                            if (ret != 0) { //如果ret不为0，就说明调用SDK出现了错误
//                                ToastUtil.showToast("抱歉，联系客服出现了错误~. error:" + ret);
//                            }
                        } catch (Exception e) {
                            ToastUtil.showToast("请确认安装了QQ客户端");
                        }
                    }
                }*/
                //电话咨询 或 在线咨询
                ActionSheetDialog dialog = new ActionSheetDialog(mActivity).builder();
                dialog.addSheetItem("在线咨询", ActionSheetDialog.SheetItemColor.Red, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        String userInfo = SpUtil.getString(Constant.CACHE_USER_INFO);
                        JSONObject jsonObject = JSON.parseObject(userInfo);
                        //姓名
                        String realname = jsonObject.getString("realname");
                        //手机号
                        String username = jsonObject.getString("username");
                        String sdktoken = UUID.randomUUID().toString();
                        Map<String, String> info = new HashMap<String, String>();
                        //sdktoken 必填
                        info.put(UdeskConst.UdeskUserInfo.USER_SDK_TOKEN, sdktoken);
                        //以下信息是可选
                        info.put(UdeskConst.UdeskUserInfo.NICK_NAME,realname);
                        info.put(UdeskConst.UdeskUserInfo.CELLPHONE,username);
                        UdeskSDKManager.getInstance().setUserInfo(mActivity, sdktoken, info);
                        //启动会话
                        UdeskSDKManager.getInstance().entryChat(mActivity);
                    }
                });
                dialog.addSheetItem("电话咨询", ActionSheetDialog.SheetItemColor.Red, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        Intent dialIntent =  new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + serverPhone));//跳转到拨号界面，同时传递电话号码
                        startActivity(dialIntent);
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    public void userInfoSuccess(MoreContentBean result) {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        mMoreContentBean = result;
        if (mMoreContentBean != null) {
            setData(mMoreContentBean);
        }
    }

    @Override
    public void showLoading(String content) {
        if (mMoreContentBean == null){
            mLoadingLayout.setStatus(LoadingLayout.Loading);
        }
    }

    @Override
    public void stopLoading() {
        mRefresh.setRefreshing(false);
    }

    @Override
    public void showErrorMsg(String msg, String type) {
        ToastUtil.showToast(msg);
        if ("网络不可用".equals(msg)){
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
        }else{
            mLoadingLayout.setErrorText(msg)
                .setStatus(LoadingLayout.Error);
        }
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.getInfo();
            }
        });
    }

    @Override
    public void onRefresh() {
        mPresenter.getInfo();
    }
}
